package in.iqing.module.content;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.squareup.picasso.Callback;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.iqing.app.R;
import in.iqing.control.helper.ImageHelper;
import in.iqing.control.util.ToastUtil;
import in.iqing.control.util.ViewUtil;
import in.iqing.model.bean.Page;
import in.iqing.model.sp.SettingSP;

/**
 * Created by neavo on 2014/9/8.
 */

public class QingIllustrationView extends FrameLayout {

    @Bind(R.id.image_view)
    public ImageView imageView;

    public QingIllustrationView(Context ctx) {
        super(ctx);

        LayoutInflater.from(getContext())
                .inflate(R.layout.widget_illustration_view, this, true);

        setBackgroundResource(SettingSP.getSingleton(ctx).getNightMode()
                ? R.drawable.content_night_bg
                : R.drawable.content_day_bg);

        ButterKnife.bind(this);
    }

    public QingIllustrationView prepare(final Page page) {
        post(new Runnable() {

            @Override
            public void run() {
                File file = new File(page.getLines().get(0));
                if (file.exists()) {
                    ImageHelper.getSingleton(getContext()).load(
                            file,
                            imageView,
                            new ExtCallback()
                    );
                } else {
                    ImageHelper.getSingleton(getContext()).load(
                            page.getLines().get(0),
                            imageView,
                            new ExtCallback()
                    );
                }
            }
        });

        return this;
    }

    private class ExtCallback implements Callback {

        @Override
        public void onError() {
            ToastUtil.show(getContext(), getContext().getString(R.string.activity_illustration_error));
        }

        @Override
        public void onSuccess() {
            int width = imageView.getWidth();
            Drawable drawable = imageView.getDrawable();
            ViewUtil.fixHeight(imageView, width, (float) drawable.getMinimumWidth() / drawable.getMinimumHeight());
        }
    }
}
